package sqlite

import (
	"time"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	gormlogger "gorm.io/gorm/logger"

	"gitee.com/csingo/cDB/logger"

	"gitee.com/csingo/cLog"

	"gitee.com/csingo/cDB/drivers"
)

type Connector struct {
	connection string
	config     *Connection
	db         *gorm.DB

	drivers.GormQuery
}

func (i *Connector) GetConnection() string {
	return i.connection
}

func (i *Connector) GetDriver() drivers.DriverInterface {
	return i.config
}

func (i *Connector) GetDB() any {
	return i.db
}

func (i *Connector) Connect() error {
	var err error
	i.db, err = gorm.Open(sqlite.Open(i.config.File), &gorm.Config{
		Logger: &logger.GormLogger{
			Config: gormlogger.Config{
				SlowThreshold:             200 * time.Millisecond,
				LogLevel:                  gormlogger.Warn,
				IgnoreRecordNotFoundError: false,
			},
		},
	})
	if err != nil {
		return err
	}

	cLog.WithContext(nil, map[string]any{
		"source":     "cDB.Connector.Connect",
		"connection": i.connection,
	}, []cLog.Option{
		cLog.IncludePaths{},
	}).Trace("创建 sqlite 连接客户端")

	return err
}

func NewSqliteConnector(connection string, config *Connection) (*Connector, error) {
	connector := &Connector{
		connection: connection,
		config:     config,
		db:         nil,
	}
	err := connector.Connect()

	return connector, err
}
